<template>
  <div class="app-container">
    <div class="top-main">
    <el-form  class="top-form-fl" :model="param" label-width="auto" :inline="true">
      <el-form-item label="售箱城市">
        <city-select :selectCity="param.carryCityIds" @cityId="startCityId" style="width: 100%;"></city-select>
      </el-form-item>

      <el-form-item label="累计销量" style="width: 400px;">
        <InputText :inputVal1="param.beginTotalRentQty" :inputVal2="param.endTotalRentQty" :inputBoxConfig="inputBoxConfig"  @inputChange="inputChange"></InputText>
      </el-form-item>
      <el-form-item label="创建日期">
        <el-date-picker v-model="param.createDate" clearable type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="编号">
        <el-input v-model.trim="param.releaseNo" clearable placeholder="输入编号"></el-input>
      </el-form-item>
    </el-form>
    <div class="top-from-fr">
        <el-button class="top-Search" @click="getTableData" type="primary">搜索</el-button>
        <el-button class="top-Refresh" @click="resetData">重置</el-button>
      </div>   
    </div>
    <cz-tages :bottomLine="true" :typeList="param.typeList" @handleTypeChange="handleTypeChange"></cz-tages>
    <span style="float: right;">
      <el-button :icon="Delete" type="danger" size="small" round @click="isDelete($event, 'pitch')"
        plain>批量删除</el-button>
      <el-button :icon="Upload" type="primary" size="small" round @click="boxPublish($event, 'pitch')"
        plain>批量上架</el-button>
      <el-button :icon="Download" type="info" size="small" round @click="boxDown($event, 'pitch')"
        plain>批量下架</el-button>
      <el-button :icon="Promotion" type="success" size="small" round @click="goBuybox" plain>发布</el-button>
    </span>

    <Table ref="tableRef" v-bind="table" @pageChange="onTablePageChange" :disableHeaderCheckbox="false" @showInfo="showInfo" @activEdite="activEdite"
      @boxPublish="boxPublish" @boxDown="boxDown" @isDelete="isDelete">
    </Table>

    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible" title="系统提示" width="500">
      <span>确认删除？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="activDelete">是的</el-button>
          <el-button type="primary" @click="param.dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
import InputText from '@/components/inputBox/inputText'
// import { getAgentSelfPage, agentSubmit, agentTobeReleased, statusCount, downPitch, deletePitch, publishPitch, getBoxNum, getBoxInfo, } from '@/api/boxRent'
import { saleBoxSelectSelfPage, deletePitch, publishPitch, downPitch, statusCount } from '@/api/boxDeal/boxSeel'
import citySelect from '@/components/citySelect'
import orderInfo from '@/store/modules/order'
import { computed, onActivated, onMounted, reactive, ref } from 'vue';
import {Plus,Delete,Promotion,Edit,Message,Download,Upload} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const param = reactive({
  loading: false,
  releaseNo:"",
  pageNum: 1,
  pageSize: 10,
  dialogVisible: false,
  stateFilter: { 5: '出售中', 10: '仓库中', 15: '待发布' },
  stateColor: { 5: '#22A86D', 10: '#2158F3', 15: '#2158F3' },
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提(次新或者适货)', },
    { value: '5', label: '全新', },
  ],
  beginTotalRentQty: '',
  endTotalRentQty: '',
  returnCityIds: [],
  carryCityIds: '',
  startCityOptions: [],
  backCityOptions: [],
  typeList: [],
  createDate:''
});

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'releaseNo', key2: 'oidContainerNo', key3: 'containerClassify', colWidth: '150', title: '编号', type: '<change>', command: 'showInfo', isCheck: true },
    { key: 'carryCityName', colWidth: '200', title: '售箱城市', type: 'cityName',width:"",height:"",isCheck: true },
    { key: 'minUnitPrice', colWidth: '80', title: '出售价格', type: 'add', currency: 'minUnitPriceCurrency', isCheck: true },
    { key: 'totalInventoryQty', colWidth: '100', title: '可售箱量', type: 'text',isTooltip: true,tooltip: "出售箱库存是卖家实际发布的出售箱数量", isCheck: true },
    { key: 'totalRentQty', colWidth: '120', title: '累计销量',sortable: true, type: 'text',isTooltip: true,tooltip: "出售箱自发布上架以来，完成提箱，并已支付买箱费，出售成功的状态为已完成订单的集装箱总数量（不含售后退款成功的订单）", isCheck: true },
    { key: 'total30RentQty', colWidth: '120', title: '30天销量',sortable: true, type: 'text',isTooltip: true,tooltip: "计算近30天的销量，销量数据以当前日期为起点，向前推算30天内完成提箱，并已完成状态的订单的集装箱数量", isCheck: true },
    { key: 'status', colWidth: '100', title: '发布状态', type: 'filter', filter: param.stateFilter, cFilter: param.stateColor, isCheck: true },
    { key: 'createTime', colWidth: '150', title: '创建日期', sortable: true, type: 'dateTime', isCheck: true },
    { key: 'updateTime', colWidth: '150', title: '更新日期', sortable: true, type: 'dateTime', isCheck: true },
    {
      key: 'operate',
      colWidth: '250',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          // content: '编辑',
          // icon: 'Edit',
          command: 'activEdite',
          name: '编辑',
          isShow: (row: { status: string; }) => {
            return row.status != '5';
          },
        },
        {
          // content: '下架',
          // icon: 'Download',
          command: 'boxDown',
          name: '下架',
          isShow: (row: { status: string; }) => {
            return row.status == '5';
          },
        },
        {
          // content: '上架',
          // icon: 'Upload',
          command: 'boxPublish',
          name: '上架',
          isShow: (row: { status: string; }) => {
            return row.status != '5';
          },
        },
        {
          // content: '删除',
          // icon: 'Delete',
          command: 'isDelete',
          name: '删除',
          isShow: (row: { status: string; }) => {
            return row.status != '5';
          },
        },

      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});

onActivated(() => {
  getTableData()
});

const startCityId = (id: string) => {
  param.carryCityIds = id
}

function handleTypeChange(val: any) {
  param.status = val
  getTableData()
}

function getTableData() {
  let data = {
    releaseSource:'5', //5-售箱公司发布 10-求购箱公司发布
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    carryCityId: param.carryCityIds,
    releaseNo:param.releaseNo?.toUpperCase(),
    // returnCityIds: param.returnCityIds,
    beginTotalRentQty: param.beginTotalRentQty - 0 || "",
    endTotalRentQty: param.endTotalRentQty - 0 || "",
    status: param.status - 0 || null
  };
  if (param.createDate) {
    data.beginCreateDate = param.createDate[0];
    data.endCreateDate = param.createDate[1];
  }
  table.config.loading = true;
  // 列表
  saleBoxSelectSelfPage(data).then((res: any) => {
    const list = JSON.parse(JSON.stringify(res.data.list));
    formatCityInfo(list)
    table.data = list
    table.config.total = res.data.total;
  });
  //汇总
  data.rentSource = 5 // 租箱来源: 5 - 集装箱公司发布 10 - 货代发布
  statusCount(data).then((res: { data: any }) => {
    const resList = res.data // [ { status: 5, totalQty: 0 },{ status: 10, totalQty: 0 },{ status: 15, totalQty: 0 } ]
    const list = [{ id: 0, name: '全部', num: 0 }, { id: 5, name: '出售中', num: 0 }, { id: 10, name: '仓库中', num: 0 }, { id: 15, name: '待发布', num: 0 }]
    param.typeList = formatStateCount(list, resList)
    table.config.loading = false;
  })
  table.config.loading = false;
}

const resetData = () =>{
  param.releaseNo = ''
  param.beginTotalRentQty = ''
  param.endTotalRentQty = ''
  param.carryCityIds = ''
  param.createDate = ''
  getTableData()
}

//编辑
const router = useRouter();
const activEdite = (row: any) => {
  if (row) {
    orderInfo().setRowData(row)
  }
  router.push('publishSellBox')
};
//详情
const showInfo = (row: any) => {
  row.isInfo=true
  if (row) {
    orderInfo().setRowData(row)
  }
  router.push('publishSellBox')
};
const goBuybox = () =>{
  orderInfo().setRowData(null)
  router.push({
    path: "publishSellBox",
    query: {
      type:"release"
    }
  })
}

//上架/下架  
const tableRef = ref({ multipleSelection: [] })
const selection = computed(() => {
  let ids: any[] = []
  tableRef.value.multipleSelection.map((item: any) => {
    ids.push(item.id)
  })
  return ids
})
const boxPublish = (row: { id: any }, opt: string) => {
  let ids: any[] = []
  if (opt == 'pitch') {
    ids = selection.value
  } else {
    ids = [row.id]
  }
  publishPitch(ids).then(() => {
    getTableData()
  })
};
const boxDown = (row: any, opt: string) => {
  let ids: any[] = []
  if (opt == 'pitch') {
    ids = selection.value
  } else {
    ids = [row.id]
  }
  downPitch(ids).then((res: any) => {
    getTableData()
  })
};

//删除 
let deleteList = ref([])
const isDelete = (row: any, opr: any) => {
  param.dialogVisible = true;
  if (opr == 'pitch') {
    deleteList.value = selection.value
  } else {
    deleteList.value = [row.id]
  }
};
const activDelete = () => {
  let ids = [...deleteList.value]
  // console.log(ids)
  deletePitch(ids).then((res: any) => {
    getTableData()
  })
  param.dialogVisible = false;
};


//分页
function onTablePageChange(page: { pageNum: number; pageSize: number }) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};


onMounted(() => {
  getTableData()

})




// 功能函数
const formatStateCount = (stateList: any, resList: any) => {
  let total = 0;
  stateList.forEach(item => {
    resList.forEach((obj: { status: number; totalQty: number }) => {
      if (item.id == obj.status) {
        item.num = obj.totalQty
        total += obj.totalQty
      }
    })
  })
  stateList.map(obj => {
    if (obj.id == 0) {
      obj.num = total
    }
  })
  return stateList
};

const formatCityInfo = (list: any) => {
  list.forEach((item: any) => {
    // 图片
    let mainFileList = JSON.parse(item.mainFileList);
    item.imgUrl = mainFileList.map((item: any) => {
      return item.url
    })[0];
  })

}

//修改输入值
const inputChange = (val1,val2) => {
  param.beginTotalRentQty = val1 // 最低值
  param.endTotalRentQty = val2 //最高值
}
const inputBoxConfig = reactive({
  placeholder1:"最低",
  placeholder2:"最高",
})

</script>